import os, sys
from subprocess import Popen, check_output, STDOUT
from threading import Thread
import socket

try:
    from PyQt5.QtCore import QRegExp,Qt
except:
    os.system("pip3 install pyqt5")
    from PyQt5.QtCore import QRegExp,Qt
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *

global o_tag
o_tag = 1

def get_ip():
    global ip, ip_pre3

    conn = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    conn.settimeout(2)
    try:
        conn.connect(("223.5.5.5",53))
        ip = conn.getsockname()[0]
        ip_pre3 = '.'.join(ip.split('.')[:3])+'.'
        #print(ip_pre3)
    except:
        ip = ''
        ip_pre3 = ''
    conn.close()

class DemoWin(QWidget):
    def __init__(self):
        super(DemoWin, self).__init__()
        self.setWindowTitle('Tools')
        self.click1_o = ''

        self.initUI()

    def initUI(self):
        # 将窗口设置为动图大小
        self.setGeometry(200, 200, 500, 309)

        #self.setFixedSize(600, 300)

        self.list = QListWidget()
        self.list.setMaximumWidth(140)

        # 设置列表内容（stack的索引）
        self.list.insertItem(0, 'Adb')
        self.list.insertItem(1, 'Clipboard')

        # 创建三个stack页面
        self.stack1 = QWidget()
        self.stack2 = QWidget()
        self.stack3 = QWidget()

        # 分别加载三个Stack的内容
        self.stack1UI()
        self.stack2UI()
        self.stack3UI()

        # 将三个stack页面加入stackWidget
        self.stackWidget = QStackedWidget()
        self.stackWidget.addWidget(self.stack1)
        self.stackWidget.addWidget(self.stack2)
        self.stackWidget.addWidget(self.stack3)

        hbox = QHBoxLayout()
        hbox.addWidget(self.list)
        hbox.addWidget(self.stackWidget)
        self.setLayout(hbox)

        # 为List绑定事件，当条目改变时，切换stack（重要）
        self.list.currentRowChanged.connect(self.stackSwitch)

        # 添加窗口标题
        self.setWindowTitle("StackWidgetDemo")

    def stack1UI(self):
        self.text1 = QTextEdit()
        self.text2 = QTextEdit()
        self.btn1 = QPushButton('adb exec-out screencap -p > ')
        self.btn2 = QPushButton('adb connect ... :5555')
        self.btn5 = QPushButton('adb reboot bootloader && fastboot flash boot ...')
        self.btn6 = QPushButton(' ')

        layout = QVBoxLayout()
        layout.addWidget(self.text1)
        layout.addWidget(self.btn1)
        layout.addWidget(self.btn2)
        layout.addWidget(self.btn5)
        layout.addWidget(self.btn6)
        layout.addWidget(self.text2)

        self.stack1.setLayout(layout)

        self.btn1.clicked.connect(self.click1)
        self.btn2.clicked.connect(self.click2)
        self.btn5.clicked.connect(self.click5)
        self.btn6.clicked.connect(self.click6)


    def stack2UI(self):

        self.text3 = QTextEdit()
        self.text4 = QTextEdit()
        self.btn3 = QPushButton('Clipboard Get ...')
        self.btn4 = QPushButton('Clipboard Cast ...')

        layout = QVBoxLayout()
        layout.addWidget(self.text3)
        layout.addWidget(self.btn3)
        layout.addWidget(self.btn4)
        layout.addWidget(self.text4)

        self.stack2.setLayout(layout)

        self.btn3.clicked.connect(self.click3)
        self.btn4.clicked.connect(self.click4)


        #label = QLabel("", self.stack2)
        #movie = QMovie("./images/timg.gif")
        #label.setMovie(movie)
        #movie.start()

    def stack3UI(self):
        label = QLabel("", self.stack3)
        label.setPixmap(QPixmap("./images/ailusha.png"))

    # 切换list时触发槽函数切换Stack
    def stackSwitch(self, index):
        self.stackWidget.setCurrentIndex(index)

    def click1(self):
        global o_tag
        #var1 = os.getcwd()
        #os.chdir(os.path.dirname(os.path.abspath(__file__)))
        c = "adb devices"
        o = '\n'+os.popen(c).read()
        c = "adb exec-out screencap -p > "+str(o_tag)+".png"
        os.system(c)
        if os.path.getsize(str(o_tag)+".png") == 0:
            self.click1_o = '执行失败 { '+c+' }\n'+self.click1_o
        else:
            self.click1_o = str(o_tag)+'.png 已检出\n'+self.click1_o
            o_tag += 1
        self.text2.setPlainText(self.click1_o+o)
        #os.chdir(var1)

    def click2(self):
        get_ip()
        global ip, ip_pre3

        i = self.text1.toPlainText()
        self.text2.setPlainText('')
        c = "adb devices"
        o = os.popen(c).read()
        try:
            i = str(int(i))
        except:
            o += '请输入整数地址'
            self.text2.setPlainText(o)
            return

        os.system("adb tcpip 5555")
        os.system("adb connect "+ip_pre3+i+":5555")
        c = "adb devices"
        o = os.popen(c).read()
        o += "请拔除有线连接"
        self.text2.setPlainText(o)

    def click3(self):
        get_ip()
        global ip, ip_pre3
        try:
            import clipboard
        except:
            os.system("pip3 install clipboard")
            import clipboard

        i = self.text3.toPlainText()
        ip_target = ip_pre3 + i
        try:
            s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            s.connect((ip_target, 1079))
        except:
            o = '连接失败 '+ip_target
            self.text4.setPlainText(o)
            return
        
        get = s.recv(131072)
        get_all = get
        while get:
            get = s.recv(131072)
            get_all += get

        get_all = get_all.split(b'0x00')[1].decode("utf-8")
        o = '收到内容'
        try:
            clipboard.copy(get_all)
            o += '已存储到了剪贴板\n\n'
        except:
            o += '\n\n'
        self.text4.setPlainText(o + get_all)

    def click4(self):
        get_ip()
        global o_tag, ip, ip_pre3
        try:
            import clipboard
        except:
            os.system("pip3 install clipboard")
            import clipboard

        self.text3.setPlainText(clipboard.paste())
        self.text4.setPlainText(ip)
        Thread(target=self.click4_thread).start()

    def click4_thread(arg):
        try:
            import clipboard
        except:
            os.system("pip3 install clipboard")
            import clipboard

        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        s.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR, 1)
        s.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
        port = 1079
        s.bind(('', port))
        s.listen(10)
        c, addr = s.accept()

        import hashlib
        send_all = hashlib.md5(clipboard.paste().encode('utf-8')).hexdigest().encode('utf-8') + b'0x00' + clipboard.paste().encode('utf-8')
        c.send(send_all)
        print(send_all)
        s.close()

    def click5(self):
        v = self.text1.toPlainText()
        if v[:8] == "file:///":
            v = v[8:]
        if not os.path.exists(v):
            o = "\"%s\"\nNot Exists\nIt should be *boot.img*" %v
            self.text2.setPlainText(o)
            return

        os.system("adb reboot bootloader")
        o = check_output(["fastboot", "flash", "boot", v], stderr=STDOUT).decode("utf-8")
        os.system("fastboot reboot")
        self.text2.setPlainText(o)

    def click6(self):
        return


if __name__ == '__main__':
    app = QApplication(sys.argv)
    app.setWindowIcon(QIcon("images/icon.ico"))
    # 创建一个主窗口
    mainWin = DemoWin()
    # 显示
    mainWin.show()
    # 主循环
    sys.exit(app.exec_())